package router

// apiRouter.go
import (
	"fmt"
	"gin/controller/api"
	"gin/model"
	"github.com/gin-gonic/gin"
	"time"
)

// https://blog.csdn.net/book_longker/article/details/123760632
// 中间件
func InitMiddleWare(ctx *gin.Context) {
	fmt.Println("1-init middle ware")
	start := time.Now().UnixNano()
	ctx.Next()
	fmt.Println("3-程序执行完成计算时间")
	end := time.Now().UnixNano()
	fmt.Println(end - start)
}

// 多个中间件
func InitMiddleWareOne(ctx *gin.Context) {
	fmt.Println("one-init middleware start")
	ctx.Next()
	fmt.Println("one-init middleware end")
}
func InitMiddleWareTwo(ctx *gin.Context) {
	fmt.Println("two-init middleware start")
	ctx.Next()
	fmt.Println("two-init middleware end")
}

func ApiRouter(r *gin.Engine) {
	apiRouter := r.Group("/api")
	{
		apiRouter.GET("/", InitMiddleWare, func(ctx *gin.Context) {
			fmt.Println("2-中间件")
			//使用公共的方法
			currentTime := model.GetDate()
			ctx.String(200, currentTime)
		})
		apiRouter.GET("/index", InitMiddleWareOne, InitMiddleWareTwo, func(ctx *gin.Context) {
			fmt.Println("首页")
			ctx.String(200, "2个中间件")
		})
		apiRouter.GET("users", InitMiddleWare, api.UserController{}.Index)
		apiRouter.GET("users/:id", api.UserController{}.List)
		apiRouter.POST("users", api.UserController{}.Add)
		apiRouter.PUT("users/:id", api.UserController{}.Update)
		apiRouter.DELETE("users/:id", api.UserController{}.Delete)
		apiRouter.GET("articles", func(ctx *gin.Context) {
			ctx.String(200, "/api/articles")
		})
	}
}
